package com.yun.modules.web;

import com.yun.modules.domain.Person;
import com.yun.modules.service.PersonService;
import com.yun.properties.DemoProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * PERSON 控制器
 *
 * @author WUWY
 * @create 2018-05-12 上午10:52
 **/
@RestController
@RequestMapping("/v0.1/demos")
public class PersonController {

    @Autowired
    private PersonService personService;
    @Autowired
    private DemoProperties properties;

    @PostMapping
    public Person save(@RequestBody @Valid Person person) {
        return personService.add(person);
    }

    /**
     * 局部更新数据
     * @param id 待更新id
     * @param modifyData 待更新的数据
     * @return
     */
    @PutMapping("/{id}")
    public Person update(@PathVariable("id") String id, @RequestBody Map<String, Object> modifyData) {
        return personService.update(id, modifyData);
    }

    @GetMapping("/{id}")
    public Person detail(@PathVariable("id") String id) {
        return personService.findStrictOne(id);
    }

    @GetMapping("/all")
    public List<Person> all() {
        return personService.findAll();
    }

    @GetMapping("")
    public Page<Person> page(@PageableDefault(value = 1, sort = {"id"}, direction = Sort.Direction.DESC)Pageable pageable) {
        return personService.page(pageable);
    }

    /**
     * 批量删除数据
     * @param ids 多个id使用逗号分隔
     */
    @DeleteMapping("/{ids}")
    public void delete(@PathVariable("ids") String[] ids) {
        for(String id : ids) {
            personService.delete(id);
        }
    }

    @GetMapping("/properties")
    public DemoProperties getProperties() {
        return properties;
    }

}
